#!/usr/bin/env python

import md5, random
import md5crypt
import os, sys

if sys.platform == 'win32':
	import fcrypt as unixcrypt
else:
	import crypt as unixcrypt

salt_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./"

# funzione generica per verificare una password
def check_pwd ( pwd, enc_pwd, enc_type = 'md5' ):
	func = globals() [ '_check_pwd_' + enc_type ]
	return func ( pwd, enc_pwd )


def _check_pwd_md5 ( pwd, enc_pwd ):
	return md5.new ( pwd ).hexdigest() == enc_pwd


def _check_pwd_unix ( pwd, enc_pwd ):
	
	if enc_pwd[:3] == '$1$':
		crypt = md5crypt
		salt = enc_pwd[3:].split ( '$', 1 )[0]
	else:
		crypt = unixcrypt
		salt = enc_pwd[:2]

	return crypt.crypt ( pwd, salt ) == enc_pwd

def _check_pwd_plain ( pwd, enc_pwd ):
	return pwd == enc_pwd


# funzione generica per cifrare una password
def encrypt_pwd ( pwd, enc_type = 'md5' ):
	func = globals() [ '_encrypt_pwd_' + enc_type ]
	return func ( pwd )


def _encrypt_pwd_md5 ( pwd ):
	return md5.new ( pwd ).hexdigest()


def _encrypt_pwd_unix ( pwd ):
	s1 = random.randrange ( len ( salt_chars ) )
	s2 = random.randrange ( len ( salt_chars ) )
	salt = salt_chars[s1] + salt_chars[s2]
	return unixcrypt.crypt ( pwd, salt )

def _encrypt_pwd_plain ( pwd ):
	return pwd

